import {
    _decorator, Button, Component, instantiate, Label, Node, tween, Tween, v3, Vec3
} from 'cc';
import EventExt from 'db://cocos-ext/base/EventExt';
import EventHelper from 'db://cocos-ext/base/EventHelper';

import { SLOT_AUTO_SPIN_START, SLOT_SHOW_AUTO_BET_PANEL } from './SlotEventType';

const { ccclass, property } = _decorator;
/** 菜单起始屏幕外位置 */
const OUT_POS: Vec3 = v3(520, -360);
/** 菜单进入UI后的位置 */
const IN_POS: Vec3 = v3(520, -10);
/** 押注数值列表 */
const BET_LIST: number[] = [100, 50, 20, 10];

/**
 * slots 多局自动押注菜单UI
 */
@ccclass('SlotBetPanel')
export default class SlotBetPanel extends Component {

    @property(Node)
    private readonly menuPanel: Node = null;

    /** menu action layer */
    @property(Node)
    private readonly menuAct: Node = null;

    /** btn countainer */
    @property(Node)
    private readonly btnLayout: Node = null;

    /** btn module node */
    @property(Node)
    private readonly btnModule: Node = null;

    onLoad() {
        this.menuPanel.on(Node.EventType.TOUCH_END, this.hide, this);
        if (!this.btnLayout || !this.btnModule)
            return;
        BET_LIST.forEach(this.createBtn.bind(this));
        this.menuPanel.active = false;
        EventExt.on(SLOT_SHOW_AUTO_BET_PANEL, this.show, this);
    }

    protected onDestroy(): void {
        EventExt.targetOff(this);
    }

    private createBtn(v: number, i: number) {
        const node: Node = i == 0 ? this.btnModule : instantiate(this.btnModule);
        if (!node) return;
        if (!node.parent)
            this.btnLayout.addChild(node);
        node.getChildByName("label").getComponent(Label).string = v.toString();
        const btn: Button = node.getComponent(Button);
        if (!btn) return;
        node.on(Button.EventType.CLICK, this.onClickSure.bind(this, v), this);
    }

    private show() {
        EventHelper.playAudio("btnClick");
        this.resetBtns(true);
        this.menuPanel.active = true;
        Tween.stopAllByTarget(this.menuAct);
        tween(this.menuAct)
            .set({ position: OUT_POS })
            .to(0.2, { position: IN_POS })
            .start();
    }

    private hide() {
        EventHelper.playAudio("uiClose");
        Tween.stopAllByTarget(this.menuAct);
        tween(this.menuAct)
            .set({ position: IN_POS })
            .to(0.1, { position: OUT_POS })
            .call(() => {
                this.menuPanel.active = false;
            })
            .start();
    }

    private resetBtns(interactable: boolean) {
        this.btnLayout.children.forEach(node => {
            node.getComponent(Button).interactable = interactable;
        });
    }

    private onClickSure(cnt: number) {
        this.resetBtns(false);
        this.hide();
        EventExt.emit(SLOT_AUTO_SPIN_START, cnt);
    }
}
